package repo

import (
	"gitee.com/tietang/terrace-go/v2/example/order"
	"gitee.com/tietang/terrace-go/v2/example/order/domain"
	"github.com/sirupsen/logrus"
	"github.com/tietang/dbx"
)

var _ domain.OrderRepository = new(OrderDao)

type OrderDao struct {
	Runner *dbx.TxRunner
}

func (o *OrderDao) Get(id int64) *order.Order {
	a := &order.Order{Id: id}
	ok, err := o.Runner.GetOne(a)
	if err != nil {
		logrus.Error(err)
		return nil
	}
	if !ok {
		return nil
	}
	return a
}

func (o *OrderDao) Save(order order.Order) (id int64, err error) {
	rs, err := o.Runner.Insert(order)
	if err != nil {
		return 0, err
	}
	return rs.LastInsertId()
}

func (o *OrderDao) UpdateStatus(order order.Order) (rows int64, err error) {
	sql := "update order set status=? where trade_no=? "
	rs, err := o.Runner.Exec(sql, order.Status, order.TradeNo)
	if err != nil {
		return 0, err
	}
	return rs.RowsAffected()
}

func (o *OrderDao) GetOne(tradeNo string) *order.Order {
	a := &order.Order{TradeNo: tradeNo}
	ok, err := o.Runner.GetOne(a)
	if err != nil {
		logrus.Error(err)
		return nil
	}
	if !ok {
		return nil
	}
	return a
}
